<template>
  <div class="app-container" style="width: 80%; margin: auto">
    <el-form
      ref="queryParms"
      :inline="true"
      :model="queryParms"
      class="demo-form-inline"
    >
      <div style="display: flex; justify-content: space-between">
        <el-form-item>
          <el-button @click="exportHandle">导出报表</el-button>
        </el-form-item>
        <!--设备选择-->
        <div>
          <el-form-item
            class="el-form-search-item"
            label="设备"
            prop="deviceId"
          >
            <el-select
              v-model="queryParms.deviceId"
              clearable
              filterable
              placeholder="请选择设备类型"
              @change="setChannelList"
            >
              <el-option
                v-for="device in deviceList"
                :key="device.zhGuid"
                :label="device.devName"
                :value="device.zhGuid"
              />
            </el-select>
          </el-form-item>
          <!--通道选择-->
          <el-form-item class="el-form-search-item" label="通道" prop="tdGuid">
            <el-select
              v-model="queryParms.tdGuid"
              clearable
              filterable
              placeholder="请选择设备类型"
            >
              <el-option
                v-for="channel in channelList"
                :key="channel.tdGuid"
                :label="channel.channelName"
                :value="channel.tdGuid"
              />
            </el-select>
          </el-form-item>

          <el-form-item class="el-form-search-item" label="告警类型">
            <el-select
              v-model="queryParms.alarmType"
              clearable
              filterable
              placeholder="请选择告警类型"
            >
              <el-option
                v-for="channel in cxdzAlarmOption"
                :key="channel.dictValue"
                :label="channel.dictLabel"
                :value="channel.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="时间范围">
            <el-date-picker
              style="width: 340px"
              v-model="queryParms.timeRange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="To"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onQuery">查询</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!-- <h1 style="text-align: center;">电压谐波报表</h1> -->
    <div>
      <div
        style="
          text-align: center;
          padding: 6px;
          border: 1px solid #dfe6ec;
          border-bottom: 0;
          font-size: 13px;
          font-weight: bold;
          color: #515a6e;
          background-color: #f5f7fa;
        "
      >
        基础数据报表
      </div>
      <el-descriptions
        class="margin-top"
        title=""
        :column="3"
        size="mini"
        border
      >
        <el-descriptions-item label="单位名称" :contentStyle="{ width: '20%' }">
          {{ deviceObj.deviceDetails.devManufacturerName }}
        </el-descriptions-item>
        <el-descriptions-item label="电压等级">
          {{
            deviceObj.channelList[0] && deviceObj.channelList[0].voltageLevel
          }}
        </el-descriptions-item>
        <el-descriptions-item label="日期/时间">
          {{ deviceObj.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="测试站点">
          {{ deviceObj.substation.substationName }}
        </el-descriptions-item>
        <el-descriptions-item label="PT变比" :contentStyle="{ width: '20%' }">
          {{
            deviceObj.channelList[0] && deviceObj.channelList[0].voltageRatio
          }}
        </el-descriptions-item>
        <el-descriptions-item label="最小短路容量(MVA)">
          {{
            deviceObj.channelList[0] && deviceObj.channelList[0].minShortCirCap
          }}
        </el-descriptions-item>
        <el-descriptions-item label="测试线路">
          {{ deviceObj.channelList[0] && deviceObj.channelList[0].channelName }}
        </el-descriptions-item>
        <el-descriptions-item label="CT变比">
          {{
            deviceObj.channelList[0] && deviceObj.channelList[0].currentRatio
          }}
        </el-descriptions-item>
        <el-descriptions-item label="用电协议容量(MVA)">
          {{ deviceObj.channelList[0] && deviceObj.channelList[0].eServAgCap }}
        </el-descriptions-item>
        <el-descriptions-item label="测试时间">
          {{ deviceObj.putDate }}
        </el-descriptions-item>
        <el-descriptions-item label="基准短路容量(MVA)">
          {{
            deviceObj.channelList[0] && deviceObj.channelList[0].baseShortCirCap
          }}
        </el-descriptions-item>
        <el-descriptions-item label="供电设备容量(MVA)">
          {{ deviceObj.channelList[0] && deviceObj.channelList[0].dEquipCap }}
        </el-descriptions-item>
      </el-descriptions>
      <el-table
        show-summary
        :summary-method="summaryMethod"
        height="calc(100vh - 250px)"
        :data="voltageReports"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="sign"
          align="center"
          label="统计项目"
        ></el-table-column>
        <el-table-column label="A相" align="center">
          <el-table-column
            prop="aMax"
            align="center"
            label="最大值"
          ></el-table-column>
          <el-table-column
            prop="aMin"
            align="center"
            label="最小值"
          ></el-table-column>
          <el-table-column
            prop="aAvg"
            align="center"
            label="平均值"
          ></el-table-column>
          <el-table-column
            prop="aTj"
            align="center"
            label="95%值"
          ></el-table-column>
          <el-table-column
            prop="aCxdz"
            align="center"
            label="国标值"
          ></el-table-column>
          <el-table-column prop="aIsNormal" align="center" label="判断">
            <template slot-scope="scope">
              <el-button
                type="text"
                :style="{ color: scope.row.aIsNormal ? '#111' : '#F35147' }"
                size="mini"
              >
                {{ scope.row.aIsNormal ? "正常" : "超标" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="B相" align="center">
          <el-table-column
            prop="bMax"
            align="center"
            label="最大值"
          ></el-table-column>
          <el-table-column
            prop="bMin"
            align="center"
            label="最小值"
          ></el-table-column>
          <el-table-column
            prop="bAvg"
            align="center"
            label="平均值"
          ></el-table-column>
          <el-table-column
            prop="bTj"
            align="center"
            label="95%值"
          ></el-table-column>
          <el-table-column
            prop="bCxdz"
            align="center"
            label="国标值"
          ></el-table-column>
          <el-table-column prop="bIsNormal" align="center" label="判断">
            <template slot-scope="scope">
              <el-button
                type="text"
                :style="{ color: scope.row.bIsNormal ? '#111' : '#F35147' }"
                size="mini"
              >
                {{ scope.row.bIsNormal ? "正常" : "超标" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="C相" align="center">
          <el-table-column
            prop="cMax"
            align="center"
            label="最大值"
          ></el-table-column>
          <el-table-column
            prop="cMin"
            align="center"
            label="最小值"
          ></el-table-column>
          <el-table-column
            prop="cAvg"
            align="center"
            label="平均值"
          ></el-table-column>
          <el-table-column
            prop="cTj"
            align="center"
            label="95%值"
          ></el-table-column>
          <el-table-column
            prop="cCxdz"
            align="center"
            label="国标值"
          ></el-table-column>
          <el-table-column prop="cIsNormal" align="center" label="判断">
            <template slot-scope="scope">
              <el-button
                type="text"
                :style="{ color: scope.row.cIsNormal ? '#111' : '#F35147' }"
                size="mini"
              >
                {{ scope.row.cIsNormal ? "正常" : "超标" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { getVoltageReportList } from "@/api/report/voltage";
import * as XLSX from "xlsx";
import FileSaver from "file-saver";
import { mapState } from "vuex";
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      queryParms: {
        timeRange: [],
        alarmType: "0",
        deviceId: "",
        tdGuid: "",
      },
      deviceObj: {
        deviceDetails: {},
        channelList: [],
        substation: {},
      },
      tableData: [], // Initialize tableData
      cxdzAlarmOption: [], // Initialize tableData
      voltageReports: [],
      channelList: [], // Initialize voltageReports
    };
  },

  computed: {
    ...mapState({
      deviceList: (state) => state.user.deviceList, // 从 Vuex 中获取 deviceList
    }),
  },
  watch: {
    queryParms: {
      handler(newForm, oldForm) {
        let obj = Object.assign({}, newForm);
        obj.device = obj.deviceId;
        obj.channel = obj.tdGuid;
        obj.datetime = obj.timeRange;
        delete obj.deviceId;
        this.$store.commit("UPDATE_FILTER_CONDITIONS", obj);
      },
      deep: true,
    },
  },

  methods: {
    setChannelList(id) {
      console.log("id", id);
      console.log("this.deviceList", this.deviceList);
      let device = this.deviceList.find((f) => f.zhGuid == id);
      if (device) {
        this.deviceObj = device;
        this.channelList = device.channelList;
        this.queryParms.tdGuid = device.channelList[0]?.tdGuid;
      }
    },
    summaryMethod({ columns, data }) {
      console.log("columns", columns);
      console.log("data", data);
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          if (
            ["aIsNormal", "bIsNormal", "cIsNormal"].includes(column.property)
          ) {
            sums[index] = data.every((e) => e[column.property] == 1)
              ? "正常"
              : "超标";
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = sums[index].toFixed(2);
          }
        } else {
          sums[index] = "N/A";
        }
      });

      return sums;
    },
    exportHandle() {
      this.ExportExcel(this.tableData);
    },
    async fetchVoltageReportList() {
      try {
        const { timeRange } = this.queryParms;
        const startTime = timeRange[0];
        const endTime = timeRange[1];
        console.log(timeRange);
        const response = await getVoltageReportList({
          startTime,
          endTime,
          ...this.queryParms,
        });
        this.voltageReports = response.data;
        this.tableData = response.data; // Assuming the table data comes from the same response
      } catch (error) {
        console.error("Failed to fetch voltage report list:", error);
      }
    },
    onQuery() {
      this.fetchVoltageReportList();
    },

    ExportExcel(ExportData) {
      const workbook = XLSX.utils.book_new();
      // 创建工作簿
      const headers = [
        "统计项目",
        "A相最大值",
        "A相最小值",
        "A相平均值",
        "A相95%值",
        "A相国标值",
        "判断",
        "B相最大值",
        "B相最小值",
        "B相平均值",
        "B相95%值",
        "B相国标值",
        "判断",
        "C相最大值",
        "C相最小值",
        "C相平均值",
        "C相95%值",
        "C相国标值",
        "判断",
      ]; // 自定义表头
      const fields = [
        "sign",
        "aMax",
        "aMin",
        "aAvg",
        "aTj",
        "aCxdz",
        "aIsNormal",
        "bMax",
        "bMin",
        "bAvg",
        "bTj",
        "bCxdz",
        "bIsNormal",
        "cMax",
        "cMin",
        "cAvg",
        "cTj",
        "cCxdz",
        "cIsNormal",
      ];
      // 定义自定义表头
      // const headers = ['日期', '姓名', '地址']; // 自定义表头
      // 定义表头对应的字段名
      // const fields = ['date', 'name', 'address'];
      // console.log(headers)
      // console.log(fields)

      // return

      // 准备数据（包括表头）
      const data = [headers];

      // 添加数据行
      ExportData.forEach((item) => {
        const row = [];
        fields.forEach((field) => {
          if (["aIsNormal", "bIsNormal", "cIsNormal"].includes(field)) {
            row.push(item[field] == 1 ? "正常" : "超标");
          } else {
            row.push(item[field]);
          }
        });
        data.push(row);
      });
      console.log(data);

      // 将数据转换为工作表
      const worksheet = XLSX.utils.aoa_to_sheet(data);

      // 设置列宽
      const colWidth = [
        { wch: 15 }, // 日期列宽
      ];
      for (let i = 0; i++; i < this.fieldsList.length + 1) {
        colWidth.push({ wch: 10 });
      }

      worksheet["!cols"] = colWidth;

      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, "表格数据");

      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
        cellStyles: true,
      });
      const blob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      let channel = this.channelList.find(
        (f) => f.tdGuid == this.queryParms.tdGuid
      );
      let device = this.deviceList.find(
        (f) => f.zhGuid == this.queryParms.deviceId
      );

      FileSaver.saveAs(
        blob,
        `${device.devName}_${channel.channelName}_${this.parseTime(
          new Date()
        )}.xlsx`
      );
      this.$message.success("导出成功"); // 提示导出成功
    },
    onReset() {
      this.queryParms.timeRange = [];
      this.voltageReports = [];
      this.tableData = [];
      this.$refs.queryParms.resetFields();
      this.fetchVoltageReportList();
    },
  },
  mounted() {
    this.fetchVoltageReportList();
  },
  created() {
    let option = this.$store.state.filterConditions.filterConditions;
    if (option) {
      this.queryParms.deviceId = option.device;
      this.queryParms.timeRange = option.datetime;
      this.setChannelList(this.queryParms.deviceId);
    }
    this.getDicts("zk_cxdz_alarm").then((response) => {
      this.cxdzAlarmOption = response.data;
    });
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-tag {
  color: #fff !important;
}

::v-deep .el-descriptions-item__cell .el-descriptions-item__content {
}

::v-deep .el-descriptions-item__label.is-bordered-label {
  background-color: #f5f7fa;
  font-size: 13px;
  font-weight: bold;
  text-align: center;
  width: 200px;
  color: #515a6e;
}

::v-deep .has-gutter {
  tr:nth-child(2) {
    display: none;
  }
}
</style>
